/* Configuration */		
	//http://212.26.144.107:1456/kadastrova-karta
	var serverMap = 'http://212.26.144.107:8092';
	//var serverMap = 'http://10.0.6.53';


	var untiled;
	var tiled;
	var pureCoverage = false;

	
	// pink tile avoidance
	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
	// make OL compute scale according to WMS spec
	OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
	
	//OpenLayers.ProxyHost = "http://212.26.144.107:4156/cgi-bin/proxy.cgi?url=";	
	OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
	  
	var map, infoo, measureControls, navControls, markers;
	//var mapBounds = new OpenLayers.Bounds(21.921242623, 43.5341787107, 42.0119321532, 53.3790101853);
	var mapBounds = new OpenLayers.Bounds(18, 44.8, 42, 52);
	var mapMinZoom = 2;
	var mapMaxZoom = 22

    // avoid pink tiles
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.Util.onImageLoadErrorColor = "transparent";
    
    
    $(document).ready(function(){    
    	var map = document.getElementById("map");
	    var leftSideWidth = 0; 
	    
	    map.style.height = (getWindowHeight()-65) + "px";	    	
	    map.style.width = (getWindowWidth()-40) + "px";
	    
	    //alert(map.style.height);
		    	
    	init();
    	  
    });

    function init(){
       OpenLayers.Lang.setCode("ru");	
    	
	   var options = {
                controls: [],
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326"),
                units: "m",
                numZoomLevels: 22,
                maxResolution: 156543.0339,
                maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)    
	   			//maxExtent: new OpenLayers.Bounds(21, 43, 42, 53)
	        };   
	     
       
	   	map = new OpenLayers.Map('map', options); 
		   	
	    initLayers();		    
	    initControls();
	    
	    map.addControl(new OpenLayers.Control.Permalink({'div': OpenLayers.Util.getElement('permalink')}));

	    if (!map.getCenter()) map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ) );        

      }// End of INIT 
    
    function initLayers()
    {
    	// if this is just a coverage or a group of them, disable a few items,
	    // and default to jpeg format
	    format = 'image/png8';
	    if(pureCoverage) {
	        format = "image/jpeg";
	    }


	   kadpodil = new OpenLayers.Layer.WMS(
                //"Кадастровий поділ", serverMap+"/vector/geoserver/gwc/service/wms?tiled=true",
                "Кадастровий поділ", serverMap+"/vector/geoserver/wms",
                {
                    LAYERS: 'kadastr',
                    STYLES: '',
                    format: 'image/png8',
                    tiled: true,
                    transparent: 'true'
                    //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                   
                },
                {
                    buffer: 0,
                    displayOutsideMaxExtent: true,
                    isBaseLayer: false,
                    yx : {'EPSG:900913' : false}
                   // transitionEffect: 'resize'
                } 
            );


            mosaic = new OpenLayers.Layer.WMS(
                "dzk:mosaic - Tiled", serverMap+"/rastr/geoserver/gwc/service/wms?tiled=true",
                {
                    LAYERS: 'dzk:mosaic',
                    STYLES: '',
                    format: 'image/jpeg',
                    tiled: true,
                    //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                },
                {
                    buffer: 0,
                    displayOutsideMaxExtent: true,
                    isBaseLayer: true,
                    yx : {'EPSG:900913' : true}
                } 
            );

/*    
var layer_wfs = new OpenLayers.Layer.Vector('Слой WFS', {
        strategies: [new OpenLayers.Strategy.Fixed({preload: true})],
        protocol: new OpenLayers.Protocol.WFS({
            version: '1.1.0',
            url: 'http://212.26.144.107:8092/vector/geoserver/wfs',
            featureType: 'obl',
            featureNS: 'http://localhost/test',
            srsName: 'EPSG:900913'
        }),
        visibility: true
}); 
*/

	var gsat = new OpenLayers.Layer.Google(
			"Google - космос",
			{type: google.maps.MapTypeId.SATELLITE, isBaseLayer: true, numZoomLevels: 22}
			// used to be {type: G_SATELLITE_MAP, numZoomLevels: 22}
	); 


	var gphy = new OpenLayers.Layer.Google(
			"Google - фізична карта",
			{type: google.maps.MapTypeId.TERRAIN}
			// used to be {type: G_PHYSICAL_MAP}
	);

	var gmap = new OpenLayers.Layer.Google(
			"Google - карта", // the default
			{numZoomLevels: 22, isBaseLayer: true}
			// default type, no change needed here
	);

	var ghyb = new OpenLayers.Layer.Google(
			"Google - космос гібрід",
			{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22}
			// used to be {type: G_HYBRID_MAP, numZoomLevels: 20}
	);


     tmsoverlay = new OpenLayers.Layer.TMS( "Карта масштабу М 1:100000", "",
            {   // url: '', serviceVersion: '.', layername: '.',
				type: 'jpg', getURL: overlay_getTileURL, alpha: true, 
				isBaseLayer: true
            });
		if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
		
    tmsoverlay_orto = new OpenLayers.Layer.TMS( "Ортофотоплани", "",
    {   // url: '', serviceVersion: '.', layername: '.',
                            type: 'jpg', getURL: overlay_getTileURL, alpha: true,
                            isBaseLayer: true
    });
    if (OpenLayers.Util.alphaHack() == false) { tmsoverlay_orto.setOpacity(0.7); }		
    
    /*tmsoverlay_orto2 = new OpenLayers.Layer.TMS( "Ортофотоплани ДЗА", "",
            {   // url: '', serviceVersion: '.', layername: '.',
                                    type: 'jpg', getURL: overlay_getTileURL, alpha: true,
                                    isBaseLayer: true
            });
    if (OpenLayers.Util.alphaHack() == false) { tmsoverlay_orto2.setOpacity(0.7); }		*/        

/*
        
            temp_parcel = new OpenLayers.Layer.WMS(
                "участки_временные", serverMap+"/geoserver/dzk/wms",
                {
                    LAYERS: 'dzk:tempdil',
                    STYLES: '',
		transparent: 'true',
                    format: format
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,
                   yx : {'EPSG:900913' : false}
                } 
            );
*/

     //map.addLayers([parcel, kadpodil, gmap, gsat, tmsoverlay,]);
    
    	markers = new OpenLayers.Layer.Markers( "Маркери" );		
		
	    map.addLayers([markers, gmap, gsat, gphy, ghyb, tmsoverlay, tmsoverlay_orto, kadpodil]);	
    }
    
    function initControls(){
    	nav = new OpenLayers.Control.NavigationHistory();        
        map.addControl(nav);
		
		var panel = new OpenLayers.Control.NavToolbar({'div':OpenLayers.Util.getElement('map_control_panel')});
		var panel_history = new OpenLayers.Control.NavToolbar({'div':OpenLayers.Util.getElement('map_control_history')});
		
		panel_history.addControls([nav.previous, nav.next]);
		
		//map.addControl(panel);	
		//map.addControl(panel_history);	

        /*map.addControl(new OpenLayers.Control.Zoom({ 
        	zoomInId: "map_zoom_in",
        	zoomOutId: "map_zoom_out"
        }));*/
        
		map.addControl(new OpenLayers.Control.DragPan({
			enableKinetic: false
		}));
		
		navControls = new OpenLayers.Control.Navigation();
        map.addControl(navControls);
        //map.addControl(new OpenLayers.Control.Scale(OpenLayers.Util.getElement('scale')));        
        //map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
		//map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('map_container_layers')}));      
		//map.addControl(new OpenLayers.Control.ZoomBox({'div':OpenLayers.Util.getElement('map_zoom_box')}));
		//map.addControl(new OpenLayers.Control.Permalink({anchor: true}));
		
		
		//map.addControl(new OpenLayers.Control.EditingToolbar(kadpodil));
		
		//map.addControl(new OpenLayers.Control.MousePosition());
		
		// style the sketch fancy
        var sketchSymbolizers = {
            "Point": {
                pointRadius: 4,
                graphicName: "square",
                fillColor: "white",
                fillOpacity: 1,
                strokeWidth: 1,
                strokeOpacity: 1,
                strokeColor: "#225086"
            },
            "Line": {
                strokeWidth: 3,
                strokeOpacity: 1,
                strokeColor: "#225086",
                strokeDashstyle: "dash"
            },
            "Polygon": {
                strokeWidth: 2,
                strokeOpacity: 1,
                strokeColor: "#225086",
                fillColor: "white",
                fillOpacity: 0.3
            }
        };
        var style = new OpenLayers.Style();
        style.addRules([
            new OpenLayers.Rule({symbolizer: sketchSymbolizers})
        ]);
        var styleMap = new OpenLayers.StyleMap({"default": style});
        
        // allow testing of specific renderers via "?renderer=Canvas", etc
        var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
        renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

        measureControls = {
            line: new OpenLayers.Control.Measure(
                OpenLayers.Handler.Path, {
                    persist: true,
                    handlerOptions: {
                        layerOptions: {
                            renderers: renderer,
                            styleMap: styleMap
                        }
                    }
                }
            ),
            polygon: new OpenLayers.Control.Measure(
                OpenLayers.Handler.Polygon, {
                    persist: true,
                    handlerOptions: {
                        layerOptions: {
                            renderers: renderer,
                            styleMap: styleMap
                        }
                    }
                }
            )
        };
        
        var control;
        for(var key in measureControls) {
            control = measureControls[key];
            control.events.on({
                "measure": handleMeasurements,
                "measurepartial": handleMeasurements
            });
            map.addControl(control);
        }
    }
    
    function initPopupInfo()
    {
    	var popup = false;
        
        infoo = new OpenLayers.Control.WMSGetFeatureInfo({
        //layerUrls: serverMap+'/vector/geoserver/wms',
        layerUrls: serverMap+'/vector/geoserver/wms',
        
	    //layers: 'dilanka',
	    //infoFormat: 'application/vnd.ogc.gml',
	    //infoFormat: 'text/html',
        infoFormat: 'text/plain',
	    title: 'Identify features by clicking',
        queryVisible: true,
        eventListeners: {
        		/*beforegetfeatureinfo: function(){
        			//alert('sdf');
        		},*/	
                getfeatureinfo: function(event) { 		
	        		
	        		
	        		//alert(event.text);
	        		
	        		var info = explode('\n', event.text);
	        		
	        		var oInfo = {
	        			koatuu : [],
	        			zone : [],
	        			quarter : [],
	        			parcel : [],
	        			natoobl : '',
	        			patoobl : '',
	        			natoray : '', 
	        			vpor : [],
	        			vposs : []
	        		};	
	        		
	        		$.each(info, function(index, row){
	        			var items = explode('=', row);	     
	        			if(items.length == 2)
	        			switch(trim(new String(items[0]))){
        					case 'koatuu':	oInfo.koatuu.push(lpad(trim(new String(items[1])), 10, '0'));break;
        					case 'zona':	oInfo.zone.push(lpad(trim(new String(items[1])), 2, '0'));break;
        					case 'kvartal':
        					case 'kvart':	oInfo.quarter.push(lpad(trim(new String(items[1])), 3, '0'));break;
        					case 'parcel':	oInfo.parcel.push(lpad(trim(new String(items[1])), 4, '0'));break;
        					case 'natoobl':	oInfo.natoobl = items[1]; break;
        					case 'natoray':	oInfo.natoray = items[1]; break;
        					case 'patoobl':	oInfo.patoobl = items[1]; break;
        					case 'vpor':	oInfo.vpor.push(items[1]); break;
        					case 'vposs': oInfo.vposs.push(items[1]); break;
        				}	        		
	        		}); 	        		
	        		
	        		//alert(dump(oInfo));
	        		var output = 'Інформацію не знайдено';
	        		if(oInfo.parcel.length > 0){        					
	        					
			        			output = '<h3>Ділянки(а)</h3>';
			        			output += '<ul>';	 
			        			$.each(oInfo.parcel, function(k, v){
			        				output += '<li>';				        					
				        				output += '<span>'+oInfo.koatuu[k]+':'+oInfo.zone[k]+':'+oInfo.quarter[k]+':'+oInfo.parcel[k]+'</span>';	
				        				var p = getParcelInfo(oInfo.koatuu[k], oInfo.zone[k], oInfo.quarter[k], oInfo.parcel[k]);
				        				if(p.length > 0){
				        					if(p[0]['ownershipvalue']) output += '<div>'+p[0]['ownershipvalue']+'</div>';
				        					if(p[0]['purpose']) output += '<div>'+p[0]['purpose']+'</div>';					        				
					        				//if(p[0]['ownershipcode']) output += '<div>'+p[0]['ownershipcode']+'</div>';					        				
					        				if(p[0]['area']) output += '<div>'+p[0]['area']+' '+p[0]['unit_area']+'</div>';
				        				}
			        				output += '</li>';	
			        			});	        		       			
			        			output += '</ul>';	 	 
							
        			}if(oInfo.parcel.length == 0 && oInfo.quarter.length > 0) // Квартал
	        		{
        				$.ajax({
							url : '/kadastrova-karta/get-Region-Info',
							dataType: 'json',
							async: false,
							data : {'koatuu' : oInfo.koatuu[0]},
 						    success :function(data){     
							
	        					output = '<h3>'+data['data']['region']+' область</h3>';
	    	        			output += '<ul>';	  
	    	        			output += '<li>';
    	        				output += '<div class="label">Район</div>';
    	        				output += '<div class="data">'+data['data']['district']+'</div>';
    	        			output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Коатуу</div>';
	    	        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
	    	        			output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Зона</div>';
	    	        				output += '<div class="data">'+oInfo.zone[0]+'</div>';
	            				output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Квартал</div>';
	    	        				output += '<div class="data">'+oInfo.quarter[0]+'</div>';
	    	        			output += '</li>';	        			
	    	        			output += '</ul>';	     	        			
							}
        				});        				 
	        			
	        		}else	if(oInfo.natoray != ''){ // Район	        		
	        			output = '<h3>'+oInfo.natoobl+' область</h3>';
		        			output += '<ul>';
		        			output += '<li>';
	        					output += '<div class="label">Район</div>';
	        					output += '<div class="data">'+oInfo.natoray+'</div>';
	        				output += '</li>';
		        			output += '<li>';
		        				output += '<div class="label">Коатуу</div>';
		        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
		        			output += '</li>';
	        			output += '</ul>';	 	        			
	        		}else if(oInfo.patoobl != ''){	// Область        		
	        			output = '<h3>'+oInfo.natoobl+' область</h3>';
	        			output += '<ul>';
		        			output += '<li>';
		        				output += '<div class="label">Коатуу</div>';
		        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
		        			output += '</li>';
	        			output += '</ul>';	        				
	        		}	 
        			

        			if (popup){
    					popup.destroy();
    					popup=false;
    			    }
        			
    		    	
    		    	popup = new OpenLayers.Popup.FramedCloud(		                   
                            "chicken", 
                            map.getLonLatFromPixel(event.xy),
                            null,
                            output,
                            null,
                            true	                     
      		        );				    
    			    popup.closeOnMove = true;
    			    popup.autoSize = true;				 
    			    map.addPopup(popup);        		
				    
                }
            }
        });
        
        map.addControl(infoo);
        infoo.activate();
    }
    
    
    function handleMeasurements(event) {
        var geometry = event.geometry;
        var units = event.units;
        var order = event.order;
        var measure = event.measure;
        var element = document.getElementById('output');
        var out = "";
        if(order == 1) {
            out += "довжина: " + measure.toFixed(3) + " " + units;
        } else {
            out += "площа: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
        }
        
        $('#draw_feature_out').html(out);
        //element.innerHTML = out;
    }

    

            
            // sets the HTML provided into the nodelist element
           /* function setHTML(response){
                document.getElementById('nodelist').innerHTML = response.responseText;
            };*/
            
            // shows/hide the control panel
            function toggleControlPanel(event){
                var toolbar = document.getElementById("toolbar");
                if (toolbar.style.display == "none") {
                    toolbar.style.display = "block";
                }
                else {
                    toolbar.style.display = "none";
                }
                event.stopPropagation();
                map.updateSize()
            }
            
            
            // Transition effect, can be null or 'resize'
            function setTransitionMode(transitionEffect){
                if (transitionEffect === 'resize') {
                    tiled.transitionEffect = transitionEffect;
                    untiled.transitionEffect = transitionEffect;
                }
                else {
                    tiled.transitionEffect = null;
                    untiled.transitionEffect = null;
                }
            }
                
            function setPalette(mode){
                if (mode == '') {
                    tiled.mergeNewParams({
                        palette: null
                    });
                    untiled.mergeNewParams({
                        palette: null
                    });
                }
                else {
                    tiled.mergeNewParams({
                        palette: mode
                    });
                    untiled.mergeNewParams({
                        palette: mode
                    });
                }
            }
            
            function setWidth(size){
                var mapDiv = document.getElementById('map');
                var wrapper = document.getElementById('wrapper');
                
                if (size == "auto") {
                    // reset back to the default value
                    mapDiv.style.width = null;
                    wrapper.style.width = null;
                }
                else {
                    mapDiv.style.width = size + "px";
                    wrapper.style.width = size + "px";
                }
                // notify OL that we changed the size of the map div
                map.updateSize();
            }
            
            function setHeight(size){
                var mapDiv = document.getElementById('map');
                
                if (size == "auto") {
                    // reset back to the default value
                    mapDiv.style.height = null;
                }
                else {
                    mapDiv.style.height = size + "px";
                }
                // notify OL that we changed the size of the map div
                map.updateSize();
            }
                                    
            function mergeNewParams(params){
                tiled.mergeNewParams(params);
                untiled.mergeNewParams(params);
            }

	        function osm_getTileURL(bounds) {
	            var res = this.map.getResolution();
	            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	            var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	            var z = this.map.getZoom();
	            var limit = Math.pow(2, z);

	            if (y < 0 || y >= limit) {
	                return "http://www.maptiler.org/img/none.png";
	            } else {
	                x = ((x % limit) + limit) % limit;
	                return this.url + z + "/" + x + "/" + y + "." + this.type;
	            }
	        }

	        function overlay_getTileURL(bounds) {
	            var res = this.map.getResolution();
	            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	            var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
	            var z = this.map.getZoom();
	            if (this.map.baseLayer.name == 'Virtual Earth Roads' || this.map.baseLayer.name == 'Virtual Earth Aerial' || this.map.baseLayer.name == 'Virtual Earth Hybrid') {
	               z = z + 1;
	            }
		        if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom ) {
	               //console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
		        //alert (map.layers[4].visibility);
		        	
		        	
				if (map.layers[5].visibility == true) {	
		               		return "http://212.26.144.107:8092/ukraine_jpg/" + z + "/" + x + "/" + y + "." + this.type
				};
				if (map.layers[6].visibility = true) {
                                return "http://212.26.144.107:8092/333/" + z + "/" + x + "/" + y + "." + this.type
                };
           
			
                } else {
			//alert;
                   return "http://www.maptiler.org/img/none.png";
                }
	        }	

		   function getWindowHeight() {
		        if (self.innerHeight) return self.innerHeight;
		        if (document.documentElement && document.documentElement.clientHeight)
		            return document.documentElement.clientHeight;
		        if (document.body) return document.body.clientHeight;
			        return 0;
		    }

		    function getWindowWidth() {
			    if (self.innerWidth) return self.innerWidth;
			    if (document.documentElement && document.documentElement.clientWidth)
			        return document.documentElement.clientWidth;
			    if (document.body) return document.body.clientWidth;
			        return 0;
		    }

		    /*function resize() {  
			    var map = document.getElementById("map");
			    var leftSideWidth = 0; 
			    
			    map.style.height = (getWindowHeight()-2) + "px";
			    
			   // if($('.sidebar').is(':visible')) leftSideWidth = 280;			    
			    	
			    map.style.width = (getWindowWidth()-2-leftSideWidth) + "px";
				if (map.updateSize) { map.updateSize(); };
		    } */
		    

		    
		  
		    

	
		    
		    //onresize=function(){ resize(); };
		    
		    
		    
		    